package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping("/loginout")
    public R logout(HttpServletRequest request){
        request.getSession().removeAttribute("user");
        return R.success("成功退出");
    }

    @PostMapping("/login")
    public R login(@RequestBody Map<String, String> map, HttpSession session){
        String phone = map.get("phone");
        String code = map.get("code");
        //Object attribute = session.getAttribute(phone);

        //从redis中获取验证码
        Object redisCode = redisTemplate.opsForValue().get(phone);

        if (redisCode == null){
            throw new CustomException("验证码还未过期");
        }

        if (redisCode != null && redisCode.equals(code)) {
            LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
            lqw.eq(User::getPhone,phone);
            User user = userService.getOne(lqw);
            if (user == null){
                user = new User();
                user.setStatus(1);
                user.setPhone(phone);
                userService.save(user);
            }else {
                if (user.getStatus() == 0){
                    return R.error("用户已被禁用");
                }
            }
            session.setAttribute("user",user.getId());
            return R.success(user);
        }
        return R.error("验证码错误");
    }

    @PostMapping("/sendMsg")
    public R sendMsg(@RequestBody Map<String, String> map, HttpSession session) {
        String code = "123456";
        String phone = map.get("phone");
        //session.setAttribute(phone,code);
        Object redisCode = redisTemplate.opsForValue().get(phone);
        if (redisCode != null){
            return R.error("验证码还未过期");
        }
        //将code存入redis缓存中
        redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);
        return R.success("验证码发送成功");
    }
}
